package wangxiaotao.config;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.util.Assert;
import sun.security.pkcs.ParsingException;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 全局日期格式化
 */
@JsonComponent
public class DateFormatConfig {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");

    /**
     * 日期格式化
     */
    public static class DateJsonSerializer extends JsonSerializer<Date>{

        @Override
        public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            //获取当前登录人的所属时区
//            dateFormat.setTimeZone(TimeZone.getTimeZone(。。。.get().getTimezone()));
            jsonGenerator.writeString(dateFormat.format(date));
        }
    }

    /**
     * 字符串解析成日期
     */
    public static class DateJsonDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            String text = jsonParser.getText();
            Assert.isTrue(text == null || "".equals(text),"转换的日期字符串为空");
            try {
                return dateFormat.parse(jsonParser.getText());
            } catch (ParseException e) {
                throw new ParsingException("字符串转换日期失败，请检查字符串是否可以转换");
            }

        }
    }
}
